package com.sea.wechat.controller;

import com.sea.wechat.response.po.NewsItemMessage;
import com.sea.wechat.response.po.NewsMessage;
import com.sea.wechat.response.po.TextMessage;
import com.sea.wechat.util.ConfigUtil;
import com.sea.wechat.util.JaxbUtil;
import com.sea.wechat.util.JedisUtil;
import com.sea.wechat.util.RedisKey;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@RestController
public class CoreController {
	
	private static final Logger log = LoggerFactory.getLogger(CoreController.class);
	
	@Autowired
	ConfigUtil configUtil;

	/**   
	 * @Title:         checkSignature   
	 * @Description:   校验服务器消息   
	 * @param:         @param request
	 * @param:         @return      
	 * @return:        String   
	 * @author:        wl  
	 * @date:          2017年7月29日 下午11:43:51   
	 * @throws   
	 */  
	@SuppressWarnings("unused")
	@RequestMapping(value="checkSignature",method=RequestMethod.GET)
	public String checkSignature(HttpServletRequest request,HttpServletResponse response){
		log.info("checkSignature:校验服务器消息【signature:"+request.getParameter("signature")
				+"====timestamp:"+request.getParameter("timestamp")
				+"====nonce:"+request.getParameter("nonce")
				+"====echostr:"+request.getParameter("nonce"));
		
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		String[] arr = new String[] { configUtil.getToken(), timestamp, nonce };  
		if(arr!=null||StringUtils.isEmpty(signature)
			||StringUtils.isEmpty(timestamp)
			||StringUtils.isEmpty(nonce)
			||StringUtils.isEmpty(echostr)){
			Arrays.sort(arr);  
			StringBuilder content = new StringBuilder();  
			for (int i = 0; i < arr.length; i++) {  
				content.append(arr[i]);  
			}  		
			String sign = DigestUtils.sha1Hex(content.toString());
			log.info("参数信息====signature:"+signature+"====timestamp:"+timestamp+"====nonce:"+nonce+"====echostr:"+echostr+"====sign:"+sign);
			if(StringUtils.isNotEmpty(signature)&& sign.equals(signature)){
				return echostr;
			}else {
				return "";
			}
		}else {
			return "";
		}
	}
	
	
	@RequestMapping(value="checkSignature",method=RequestMethod.POST)
	public String getMessage(HttpServletRequest request,HttpServletResponse response){
		log.info("getMessage:接收服务器消息");
		StringBuilder builder = null;
			try {
				builder = new StringBuilder();
//				byte[] xml = HttpUtils.getByte(request.getInputStream());
				byte[] xml = IOUtils.toByteArray(request.getInputStream());
				builder.append(new String(xml,"UTF-8"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			//讲用户的openid存入redis
			log.info("接收到服务器消息:"+builder.toString());
			if(StringUtils.isEmpty(builder.toString())){
				return "";
			}else {
				TextMessage obj = JaxbUtil.converyToJavaBean(builder.toString(), TextMessage.class);
				List<String> users = JedisUtil.lrange(RedisKey.USER, 0L, -1L);
				if(users!=null && users.contains(obj.getFromUserName())){
				}else {
					JedisUtil.lpush(RedisKey.USER, obj.getFromUserName());
				}
				//返回一个图文消息
				List<NewsItemMessage> list = new ArrayList<NewsItemMessage>();
				NewsItemMessage item = new NewsItemMessage();
				item.setTitle("测试标题");
				item.setDescription("测试简介内容。");
				item.setPicUrl("http://seopic.699pic.com/photo/00013/6720.jpg_wh1200.jpg");
				item.setUrl("http://114.215.164.66/test/index");
				list.add(item);
				NewsMessage message = new NewsMessage();
				message.setToUserName(obj.getFromUserName());
				message.setFromUserName(obj.getToUserName());
				message.setCreateTime(System.currentTimeMillis());
				message.setMsgType("news");
				message.setArticleCount("1");
				message.setArticles(list);	
				
				TextMessage text = new TextMessage();
				text.setFromUserName(obj.getToUserName());
				text.setToUserName(obj.getFromUserName());
				text.setCreateTime(System.currentTimeMillis()/1000);
				text.setMsgType("text");
				text.setContent("&lt;a href=&quot;http://www.2345.com/?k381740148&quot;&gt;这是个超链接&lt;/a&gt;");
				return JaxbUtil.convertToXml(text);
			}
	}
	
	@RequestMapping(value="test")
	public String test(){
		return "测试请求成功";
	}
	
	public static void main(String[] args) {
//		String xml = "<xml><ToUserName><![CDATA[gh_d92f17b3940e]]></ToUserName><FromUserName><![CDATA[o2mDP0YpS5s0C3IMxoU7XrpdEbQ8]]></FromUserName><CreateTime>1501640998</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你好]]></Content><MsgId>6449498977160564382</MsgId></xml>";
//		TextMessage obj = JaxbUtil.converyToJavaBean(xml, TextMessage.class);
//		System.out.println(JSONObject.toJSON(obj));
//		System.out.println(JedisUtil.hexists("user", "o2mDP0YpS5s0C3IMxoU7XrpdEbQ8"));
		List<NewsItemMessage> list = new ArrayList<NewsItemMessage>();
		NewsItemMessage item = new NewsItemMessage();
		item.setTitle("测试标题");
		item.setDescription("测试简介");
		item.setPicUrl("1312");
		item.setUrl("3213");
		list.add(item);
		NewsMessage message = new NewsMessage();
		message.setToUserName("1231");
		message.setFromUserName("312");
		message.setCreateTime(System.currentTimeMillis());
		message.setMsgType("news");
		message.setArticleCount("1");
		message.setArticles(list);

		
		TextMessage text = new TextMessage();
		text.setFromUserName("123");
		text.setToUserName("321");
		text.setCreateTime(System.currentTimeMillis());
		text.setMsgType("text");
		text.setContent("超链接:<a href=\"http://www.baidu.com\">跳转</a>");
//		System.out.println(StringEscapeUtils.escapeXml("超链接:<a href=\"http://www.baidu.com\">跳转</a>"));
//		System.out.println(JaxbUtil.convertToXml(text));
	}
}
